/**
 * 封装请求
 */
import axios from 'axios'
import router from '../router'
import { Message } from 'element-ui'
import { getLocalStorage } from './localStorage'
import { baseUrl } from './env'
// import * as Sentry from '@sentry/browser'
axios.defaults.baseURL = baseUrl

// 请求错误统一处理
axios.interceptors.request.use(config => {
  return config
}, err => {
  Message.error({ message: '请求超时!' })
  return Promise.resolve(err)
})
axios.interceptors.response.use(data => {
  if (data.status && data.status < 400) {
    if (data.data.code && data.data.code !== 'ok') {
      // _codeInquire(data.data.code)
      Message.error({ message: data.data.message || data.data.msg })
      // code: 'staff_token_timeout'  ===>   token过期
      if (data.data.code === 'staff_token_timeout') {
        setTimeout(() => {
          router.replace('/login')
        }, 500)
      }
      if (data.data.code === 'need_captcha') {
        return data
      }
      return ''
    }
  }
  return data
}, err => {
  if (!err.response) {
    // 有可能存在服务不启动的场景（测试时），所以做了处理
    Message.error({ message: '服务未启动' })
  } else if (err.response.status === 504 || err.response.status === 404) {
    // 404不存在
    Message.error({ message: '服务器出现错误，请联系系统管理员∥' })
  } else if (err.response.status === 403 || err.response.status === 401) {
    // 403 正常 token 过期或无效状态码，401 是 postgrest 的 token 过期或无效状态码
    Message.error({ message: '权限不足,请重新登录' })
    setTimeout(() => {
      router.replace('/login')
    }, 500)
  } else if (err.response.status === 416) {
    Message.error({ message: '超出数据最大值，没有数据' })
  } else if (err.response.status === 422) {
    Message.error({ message: '请填写完整的信息' })
  } else if (err.response.status === 603) {
    Message.error({ message: '导出数据失败！' })
  } else {
    Message.error({ message: '网络请求错误，请刷新页面' })
  }
  // Sentry.captureException(err)
  // 将错误统一处理，然后返回空字符串
  return Promise.resolve('')
})

/**
 * @description get请求
 * @param {String} url 请求接口
 * @param {Object} [params] 请求参数
 * @param {Object} [headers] 请求头
 * @param {Boolean} [needHeader] 是否携带token
 * @param {Boolean} [page] 是否允许分页
 * @param {string} [query] 携带在链接上参数
 */
export function fetch (url, params = {}, headers = {}, needHeader, page, query = '') {
  return new Promise((resolve, reject) => {
    if (!headers || JSON.stringify(headers) === '{}') {
      headers = { 'Content-Type': 'application/json' }
    } else {
      headers = {
        'Content-Type': 'application/json',
        ...headers
      }
    }
    if (page) {
      headers.Prefer = 'count=exact'
      headers['Range-Unit'] = 'items'
    }
    if (needHeader) {
      const token = getLocalStorage('sps_token') || ''
      headers.Authorization = token
    }
    url += query
    axios.get(url, { params, headers }).then(response => {
      let data = response.data || response
      if (page) {
        data = response
      }
      resolve(data)
    }).catch(err => {
      // Sentry.captureException(err)
      reject(err)
    })
  })
}

/**
 * @description post请求
 * @param {String} url 请求接口
 * @param {Object} [params] 请求参数
 * @param {Object} [headers] 请求头
 * @param {Boolean} [needHeader] 是否携带token
 */
export function post (url, params = {}, headers = {}, needHeader) {
  return new Promise((resolve, reject) => {
    if (!headers || JSON.stringify(headers) === '{}') {
      headers = { 'Content-Type': 'application/json' }
    } else {
      headers = {
        'Content-Type': 'application/json',
        ...headers
      }
    }
    if (needHeader) {
      const token = getLocalStorage('sps_token') || ''
      headers.Authorization = token
    }
    axios.post(url, params, { headers }).then(response => {
      const data = response.data || response
      resolve(data)
    }).catch(err => {
      // Sentry.captureException(err)
      reject(err)
    })
  })
}

/**
 * @description patch请求
 * @param {String} url 请求接口
 * @param {Object} [params] 请求参数
 * @param {Object} [headers] 请求头
 * @param {Boolean} [needHeader] 是否携带token
 * @param {string} [query] 携带在链接上参数
 */
export function patch (url, params = {}, headers = {}, needHeader, query = '') {
  return new Promise((resolve, reject) => {
    if (!headers || JSON.stringify(headers) === '{}') {
      headers = { 'Content-Type': 'application/json' }
    } else {
      headers = {
        'Content-Type': 'application/json',
        ...headers
      }
    }
    if (needHeader) {
      const token = getLocalStorage('sps_token') || ''
      headers.Authorization = token
    }
    url += query
    axios.patch(url, params, { headers }).then(response => {
      const data = response.data || response
      resolve(data)
    }).catch(err => {
      // Sentry.captureException(err)
      reject(err)
    })
  })
}

/**
 * @description put请求
 * @param {String} url 请求接口
 * @param {Object} [params] 请求参数
 * @param {Object} [headers] 请求头
 * @param {Boolean} [needHeader] 是否携带token
 * @param {string} [query] 携带在链接上参数
 */
export function put (url, params = {}, headers = {}, needHeader, query = '') {
  return new Promise((resolve, reject) => {
    if (!headers || JSON.stringify(headers) === '{}') {
      headers = { 'Content-Type': 'application/json' }
    } else {
      headers = {
        'Content-Type': 'application/json',
        ...headers
      }
    }
    if (needHeader) {
      const token = getLocalStorage('sps_token') || ''
      headers.Authorization = token
    }
    url += query
    axios.put(url, params, { headers }).then(response => {
      const data = response.data || response
      resolve(data)
    }).catch(err => {
      // Sentry.captureException(err)
      reject(err)
    })
  })
}

/**
 * @description del请求
 * @param {String} url 请求接口
 * @param {Object} [params] 请求参数
 * @param {Object} [headers] 请求头
 * @param {Boolean} [needHeader] 是否携带token
 * @param {string} [query] 携带在链接上参数
 */
export function del (url, params = {}, headers = {}, needHeader, query = '') {
  return new Promise((resolve, reject) => {
    if (!headers || JSON.stringify(headers) === '{}') {
      headers = { 'Content-Type': 'application/json' }
    } else {
      headers = {
        'Content-Type': 'application/json',
        ...headers
      }
    }
    if (needHeader) {
      const token = getLocalStorage('sps_token') || ''
      headers.Authorization = token
    }
    url += query
    axios.delete(url, { params, headers: { ...headers } }).then(response => {
      const data = response.data || response
      resolve(data)
    }).catch(err => {
      // Sentry.captureException(err)
      reject(err)
    })
  })
}

const _codeTable = {
  ok: '成功',
  system_error: '系统错误',
  captcha_error: '验证码错误',
  need_captcha: '需要填写验证码',
  verify_faild: '账号密码错误',
  org_disabled: '组织已禁用',
  staff_token_invalid: '成员token无效',
  staff_token_timeout: 'token超时，请重新登录',
  not_belong_org: '不属于当前组织',
  default: '未知错误'
}

export function _codeInquire (code) {
  const result = _codeTable[code] || _codeTable.default
  Message.error({ message: result })
}
